package naga.x.platform2.channel.qunhei;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import naga.x.platform2.app.Channel;
import naga.x.platform2.app.model.GameServer;
import naga.x.platform2.app.model.Recharge;
import naga.x.platform2.app.model.RechargeTemplate;
import naga.x.platform2.app.support.GameServerSupport;
import naga.x.platform2.app.support.RechargeSupport;
import naga.x.platform2.channel.qunhei.support.QunHeiApi;
import naga.x.platform2.channel.qunhei.support.QunHeiConfig;
import naga.x.platform2.channel.s399.support.S399Api;
import naga.x.platform2.support.RequestPath;
import naga.x.platform2.utils.NumberUtils;

/**
 * 群黑游戏
 * @see <a href="http://admin.qunhei.com/Upload/port/#api-User-Login">群黑游戏API</a>
 * @author yang.li
 *
 */
@Controller
public class QunHeiController {
	
	@Autowired
	private QunHeiApi api;
	@Autowired
	private QunHeiConfig config;
	@Autowired
	private RechargeSupport support;
	@Autowired
	private GameServerSupport gameServers;
	
	private static Channel channel = Channel.QUNHEI;
	
	private static final Logger LOG = LoggerFactory.getLogger(QunHeiController.class);

	@RequestMapping(path = RequestPath.QUNHEI_LOGIN)
	public String login(@RequestParam("username") String uid, String serverid, String time, String isadult,
			@RequestParam(value = "uimg", required = false) String headimgurl, @RequestParam(value = "nname", required = false) String nickname,
			String unid, String flag) {
//		username=62&serverid=1&time=134234562&isadult=1&nname=张晓珊&unid=test123&flag=test111111&uimg=xxxx
//		username	String 玩家id(唯一)
//		serverid	Number 游戏服务器,(如果游戏有内置服务器选择，则改参数为固定值1)
//		time	Number 登录时间(UNIX时间戳)
//		isadult	Number 防沉迷标识(1是成年，0是未成年)
//		uimg 可选	String 玩家头像
//		nname 可选	String 玩家昵称
//		unid 可选	String 玩家来源
//		flag	String 验证签名，md5(username+serverid+isadult+time+key) 这里传递的md5字串为小写字母, 这里的key是提交到后台的登录key，加号为连接符
		String sign = QunHeiApi.makeSign(config.getLoginKey(), new String[] { uid, serverid, isadult, time });
		if (sign.equals(flag)) {
			return api.createLoginRedirectUrl(uid, nickname, headimgurl);
		}
		return api.createLoginErrorRedirectUrl(S399Api.Code.SIGN_ERROR);
	}
	
	@RequestMapping(path = RequestPath.QUNHEI_PAY, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public Object pay(Integer sid, Long pid, Integer product, String uid, String name) {
		GameServer gs = gameServers.get(sid);
		if (gs == null) {
			return api.createError(S399Api.Code.SERVER_NOT_FOUND);
		}
		if (pid == null) {
			return api.createError(S399Api.Code.PLAYER_ID_ERROR);
		}
		RechargeTemplate template = support.getTemplate(product);
		if (template == null) {
			return api.createError(S399Api.Code.RECHARGE_PRODUCT_NOT_FOUND);
		}
		return api.createOrder(sid, uid, pid, name, template);
	}
	
	@RequestMapping(path = RequestPath.QUNHEI_PAY_CALLBACK, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public String payCallback(String serverid, String orderno, @RequestParam(value = "username", required = false) String uid,
							String addgold, String rmb, String paytime, String ext, String sign) {
//		serverid	Number 游戏服务器，如果游戏有内置服务器选择，该参数则为默认值1
//		orderno	String 订单号,不允许重复
//		username	Number 充值账号
//		addgold	Number 充值金币数量
//		rmb	Number 充值人民币，单位元
//		paytime	Number 订单时间戳
//		ext	String 充值透传参数，是唤起支付页面接口参数原样返回
//		sign	String 验证签名，签名方式为：MD5(orderno+username + serverid+addgold + rmb+paytime+ext+key)这里的key是提交到后台的充值key,加号为连接符
		String s = QunHeiApi.makeSign(config.getPayKey(), new String[] { orderno, uid, serverid, addgold, rmb, paytime, ext });
		if (!s.equals(sign)) {
			LOG.info("[QUNHEI PAY ERR]SERVER[{}]ORDER[{}]UID[{}]ADDGOLD[{}]RMB[{}]PAYTIME[{}]EXT[{}]SIGN[{}]SIGN2[{}]CAUSE[SIGNERR]",
					serverid, orderno, uid, addgold, rmb, paytime, ext, sign, s);
			return QunHeiApi.SDKCode.SIGN_ERROR.toString();
		}
		S399Api.PayInfo payInfo = QunHeiApi.parsePayInfo(ext);
		GameServer gs = gameServers.get(payInfo.serverId);
		if (gs == null) {
			LOG.info("[QUNHEI PAY ERR]SERVER[{}]ORDER[{}]UID[{}]ADDGOLD[{}]RMB[{}]PAYTIME[{}]EXT[{}]SIGN[{}]CAUSE[GSERR]",
					serverid, orderno, uid, addgold, rmb, paytime, ext, sign);
			return QunHeiApi.SDKCode.USER_NOT_EXIST.toString();
		}
		RechargeTemplate product = support.getTemplate(payInfo.productId);
		if (product == null) {
			LOG.info("[QUNHEI PAY ERR]SERVER[{}]ORDER[{}]UID[{}]ADDGOLD[{}]RMB[{}]PAYTIME[{}]EXT[{}]SIGN[{}]CAUSE[PRODUCTERR]",
					serverid, orderno, uid, addgold, rmb, paytime, ext, sign);
			return QunHeiApi.SDKCode.USER_NOT_EXIST.toString();
		}
		int money = (int) NumberUtils.parseFloat(rmb);
		if (money < product.getPrice()) {
			LOG.info("[QUNHEI PAY ERR]SERVER[{}]ORDER[{}]UID[{}]ADDGOLD[{}]RMB[{}]PAYTIME[{}]EXT[{}]SIGN[{}]CAUSE[MONEYERR]",
					serverid, orderno, uid, addgold, rmb, paytime, ext, sign);
			return QunHeiApi.SDKCode.USER_NOT_EXIST.toString();
		}
		Recharge entity = new Recharge(channel.prefix + orderno, payInfo.playerId, payInfo.serverId, money, product.getStone(), product.getId(), channel.name);
		entity.setChannelUid(channel.withPrefix(uid));
		boolean succ = support.offer(entity);
		LOG.info("[QUNHEI PAY SUCC]SERVER[{}]ORDER[{}]UID[{}]ADDGOLD[{}]RMB[{}]PAYTIME[{}]EXT[{}]SIGN[{}]SUCC[{}]",
				serverid, orderno, uid, addgold, rmb, paytime, ext, sign, succ ? 1 : 0);
		return succ ? QunHeiApi.SDKCode.PAY_SUCC.toString() : QunHeiApi.SDKCode.ORDER_DUPLICATED.toString();
	}
	
	
}
